<?php
require_once("../system/load.inc.php");
//require_once("../system/config.php");
	class REST {
		/***************************
			List of Agrument
		***************************/
		protected $_allow = array();
		
		protected $_content_format;
		
		protected $_request = array();
		
		protected $_method = "";
		
		protected $_code = 200;
		
		protected $config;

		protected $_params_request = array();
		
		/*****************************
			Start Web Service
		*****************************/
		public function __construct(){
			$this->inputs();
			
			$this->config = &get_config();
			
			//Create a obj format
			$this->config['formater'] = &load_class('Format','lib','');
			
			//Create a obj Security
			//$this->config['security'] = &load_class('Security','scrt');
			
		}
		// . Get status message from web service
		/*
		*
		*/
		private function get_status_message(){
			$status = $this->config['Status'];
			return;// ($status[$this->_code])?$status[$this->_code]:$status[500];
		}
		protected function get_referer(){
			return $_SERVER['HTTP_REFERER'];
		}
		/*
		* Get format output
		*/
		protected function set_format($format){
			$this->_content_format = $format;
		}
		
		/*. creates the response
		*
		*/
		protected function response($data, $status){
			// If data is empty and not code provide, error and bail
			if (empty($data) )
			{
				$http_code = 404;

				// create the output variable here in the case of $this->response(array());
				$output = NULL;
			}
			// If data is empty but http code provided, keep the output empty
			else if (empty($data) && is_numeric($http_code))
			{
				$output = NULL;
			}
			$this->_code = ($status)?$status:200;
			$this->set_headers();
			
			//** Viet them phan chuyen doi Format giua cac xml va json
			
			if (strcasecmp($this->_content_format,'html') == 0){
				$output = $this->config['formater']->to_html($data);
				exit($output);
			}
			else if (strcasecmp($this->_content_format,'xml') == 0){
				$output = $this->config['formater']->to_xml($data);
				exit($output);
			}
			else if (strcasecmp($this->_content_format,'csv') == 0){
				$output = $this->config['formater']->to_csv($data);
				exit($output);
			}
			else{
				$output = $this->config['formater']->to_json($data);
				exit($output);
			}
		}
		protected function set_headers(){
			header("HTTP/1.1 ".$this->_code." ".$this->get_status_message());
			if(strcasecmp($this->_content_format,'xml') == 0)
				header("Content-Type:".$this->config['content_type']['xml']."; charset=utf-8");
			else if (strcasecmp($this->_content_format,'html') == 0)
				header("Content-Type:".$this->config['content_type']['html']."; charset=utf-8");
			else //if(strcasecmp($this->_content_format,'json') == 0)
				header("Content-Type:".$this->config['content_type']['json'].";charset=utf-8");	
		}
		// . Detect https
		/*
		*
		*/
		protected function _detect_ssl()
		{
				return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on");
		}
		/*
		*	detect authentication
		*/
		protected function _detect_authentication()
		{
			if( $this->config['authentication_required'] == TRUE ){
				if( empty($_REQUEST['username']) || empty($_REQUEST['password']) ){
					$error = array('status' => "Failed", "msg" => "Unauthorized - Login to do somthing");
					$this->response($error,401);
				}
				else if(empty($_REQUEST['username'])=='tuan' && empty($_REQUEST['password']) == '12345')
				{
					$this->authentication_required = FALSE;
					return FALSE;
				}
			}
		}
		
		
		//. Detect Method input
		/*
		*
		*/
		public function _get_request_method(){
			$method = isset($_SERVER['REQUEST_METHOD'])?$_SERVER['REQUEST_METHOD']:"";
			if($method == "")
				return 'get';
			return $_SERVER['REQUEST_METHOD'];
		}
		
		private function inputs(){
			switch($this->_get_request_method()){
				case "POST":
					$this->_request = $this->cleanInputs($_POST);
					break;
				case "GET":
				case "DELETE":
					$this->_request = $this->cleanInputs($_GET);
					break;
				case "PUT":
					parse_str(file_get_contents("php://input"),$this->_request);
					$this->_request = $this->cleanInputs($this->_request);
					break;
				default:
					$this->response('',406);
					break;
			}
		}		
		
		private function cleanInputs($data){
			$clean_input = array();
			if(is_array($data)){
				foreach($data as $k => $v){
					$clean_input[$k] = $this->cleanInputs($v);
				}
			}else{
				if(get_magic_quotes_gpc()){
					$data = trim(stripslashes($data));
				}
				$data = strip_tags($data);
				$clean_input = trim($data);
			}
			return $clean_input;
		}		
		
		
		/*
		*	Process incoming Data
		*/
		
		protected function parseIncomingParams()
		{
			$parameters = array();
 
			// lay gia tri tu method GET
			if (isset($_SERVER['QUERY_STRING'])) {
				parse_str($_SERVER['QUERY_STRING'], $parameters);
			}
			// lay gia tri cua POST/PUT method la ghi de len $parameter o GET

			$body = @file_get_contents("php://input");
			if(empty($body))
				$this->response(array('status'=>'Failed', 'Message'=>'Cant find any data from Client!'),404);
			$content_type = false;
			if(isset($_SERVER['CONTENT_TYPE'])) {
				$content_type = $_SERVER['CONTENT_TYPE'];
			}
			switch($content_type) {
				case "application/json":
					$body_params = json_decode($body,true);
					return $body_params;
					if($body_params) {
						foreach($body_params as $param_name => $param_value) {
							$parameters[$param_name] = $param_value;
						}
					}
					break;
				default:
					// them mot so content-type: application/xml, html
					break;
			}
			$this->_request = $parameters;
		}
		protected function _parse_get()
		{
			parse_str(parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY), $get);

			$this->_requset = array_merge($this->_requset, $get);
		}
		
		protected function _parse_post()
		{
			$this->_request['body'] = file_get_contents('php://input');
			var_dump($this->_request);
		}
		
		protected function _parse_put()
		{
			$this->_request['body'] = file_get_contents('php://input');
		}
		
		protected function _parse_delete()
		{
			parse_str(file_get_contents('php://input'), $this->_request);
		}
		
		protected function _xss_clean($val, $process)
		{
			return $process ? $this->config['security']->xss_clean($val) : $val;
		}
		
		/*
		*	process Author
		*/
		protected function _detected_login()
		{
			if ((!isset($_SERVER['PHP_AUTH_USER'])) || (!isset($_SERVER['PHP_AUTH_PW']))) {
				header('WWW-Authenticate: Basic realm="Secured Area"');
				$error = array('Status'=>'Login require','Message'=>'Authorization Required.');
				$this->response($error,404);
			} 
			else if ((isset($_SERVER['PHP_AUTH_USER'])) && (isset($_SERVER['PHP_AUTH_PW'])))
			{
				if (($_SERVER['PHP_AUTH_USER'] != "tuanhd") || ($_SERVER['PHP_AUTH_PW'] != "123456")) {
				   header('WWW-Authenticate: Basic realm="Secured Area"');
				   $error = array('Status'=>'Login require','Message'=>'Authorization Required - Account or Password is not correct');
				   $this->response($error,404);
				} else if (($_SERVER['PHP_AUTH_USER'] == "tuanhd") || ($_SERVER['PHP_AUTH_PW'] == "tuanhd")) {
					$this->response(array('Status'=>'Login success'),200);
				}
			}
		}
	}	
?>